<?php

class CacheBuster
{
    const CSS_TYPE = 'cssType';
    const SMARTY_TEMPLATE_TYPE = 'SmartyTemplateType';

    private $contentType;
    private $replacePatterns = array(
        self::CSS_TYPE => '/(url\([\"|\'])(\S+)\.(gif|jpg|png|ico)/i',
        self::SMARTY_TEMPLATE_TYPE => '/(href="|src="|data-original="){0,1}(\S+)\.(txt|xml|gif|jpg|png|ico|swf|mp3|mp4)/i'
    );

    public function __construct($contentType)
    {
        $this->contentType = $contentType;
    }

    public function SetContentType($contentType)
    {
        $this->contentType = $contentType;
    }

    public function PrepareTemplateVars($templateVars)
    {
        $this->SetContentType(self::SMARTY_TEMPLATE_TYPE);
        foreach ($templateVars as &$templateVar)
        {
            $templateVar = $this->PrepareTemplateVar($templateVar);
        }
        unset($templateVar);
        return $templateVars;
    }

    public function ModifyContent($content)
    {
        $replacePattern = $this->replacePatterns[$this->contentType];
        return preg_replace_callback($replacePattern, array($this, 'ReplaceCallback'), $content);
    }

    private function ReplaceCallback($matches)
    {
        $fileUrl = $matches[2] . '.' . $matches[3];
        $realFilePath = self::GetRealFilePath($fileUrl);
        $suffix = '';
        if ( file_exists($realFilePath) )
        {
            $suffix = '_' . filemtime($realFilePath);
        }
        return  $matches[1] . $matches[2] . $suffix . '.' . $matches[3];
    }

    private function GetRealFilePath($url)
    {
        if ($this->contentType == self::SMARTY_TEMPLATE_TYPE)
        {
            $url = $this->FixPathToVideo($url);
        }
        $realFilePath = ROOT_PATH . 'content' . $url;
        return $realFilePath;
    }

    private function FixPathToVideo($url)
    {
        $searchPattern = '/^(\/video\/\d+x\d+\/)/i';
        $replacement = '/resources/';
        return preg_replace($searchPattern, $replacement, $url);
    }

    private function PrepareTemplateVar($variable)
    {
        if ( is_string($variable) )
        {
            $variable = $this->ModifyContent($variable);
        }
        else if ( is_array($variable) )
        {
            foreach ($variable as &$item)
            {
                $item = $this->PrepareTemplateVar($item);
            }
            unset($item);
        }
        return $variable;
    }
}

?>